package com.backend.securitiessystem.exception;

import com.backend.securitiessystem.enums.AppHttpCodeEnum;
import com.backend.securitiessystem.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 136062021111-涂煜峰
 */
@RestControllerAdvice  //控制器增强类
@Slf4j
public class ExceptionCatch {

    /**
     * 处理可控异常  自定义异常
     */
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public static Result<Exception> exception(BaseException e) {
        log.error("An error occurred: {}", e.getMessage(), e);
        return Result.errorResult(e.getAppHttpCodeEnum());
    }

    /**
     * 处理不可控异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Exception> exception(Exception e) {
        log.error("catch exception:{}", e.getMessage(), e);
        return Result.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 参数不匹配异常,处理表单提交的参数异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<Exception> bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        List<String> collect = fieldErrors.stream().map(item -> {
            if (Objects.requireNonNull(item.getDefaultMessage()).contains("NumberFormatException")) {
                return "数据类型错误";
            }

            return item.getDefaultMessage();
        }).collect(Collectors.toList());

        return Result.errorResult(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), String.valueOf(collect));
    }

    /**
     * 处理 json 请求体调用接口校验失败抛出的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Exception> methodArgumentNotValidExceptionHandler(
            MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return Result.errorResult(AppHttpCodeEnum.PARAM_REQUIRE.getCode(), String.valueOf(collect));
    }

}

